package com.zxc.fastjson;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.reflect.FieldUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.fastjson.util.ParameterizedTypeImpl;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.reader.ObjectReader;

public class List2MapCodec implements ObjectDeserializer {

	@Override
	public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
		
		sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl destType = (sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl) type;
	        
        Type[]  actualTypeArguments = {destType.getActualTypeArguments()[1]};
	        
        ParameterizedTypeImpl orgType = new ParameterizedTypeImpl(actualTypeArguments, null, List.class);
		
		JSONReader reader = parser.getLexer().getReader();
        ObjectReader<?> objectReader = reader.getContext().getObjectReader(orgType);
       
        Object orgObj = objectReader.readObject(reader, orgType, fieldName, 0L);
		List<?> list = (List<?>) orgObj;
        
//		destType.getActualTypeArguments()[0];
//		destType.getActualTypeArguments()[1];
		
		Map<Object,Object> m= list.stream().collect(Collectors.toMap(key->{try {
			return FieldUtils.readDeclaredField(key, "name", true);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			return key;
		}}, value->value));
		
		return (T) m;
	}

}
